<template>
  <div class="supplier-and-contract">
    <div class="block">
      <header>
        <h2 class="required">
          供应商选择
        </h2>
      </header>
      <section>
        <el-form>
          <el-form-item label="供应商">
            <el-select v-model="supplier_id" placeholder="请选择" @change="onChangeSupplier" :disabled="disabled">
              <el-option
                v-for="item in rows_supplies"
                :key="item.shortCode"
                :label="item.orgName"
                :value="item.shortCode"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </section>
    </div>
    <div class="block select-contract-part">
      <header>
        <h2 class="required">
          授权医院选择
        </h2>
      </header>
      <section class="select-contract-table">
        <el-radio-group v-model="contract_id" class="w100p" @change="onChangeContract">
          <el-editable
            v-loading="contractTableLoading || productLoading"
            :columns="COLUMNS_CONTRACT"
            :data="payload_contracts"
            height="200"
            @reload="onLoadData"
          >
            <template v-slot:default-checkbox="{ row }">
              <el-radio :label="row.accountNumber">
                {{ '' }}
              </el-radio>
            </template>
          </el-editable>
        </el-radio-group>
      </section>
    </div>
    <el-dialog
      title="更换供应商"
      :visible.sync="dialogVisible.supplier"
      width="30%"
      :before-close="handleCloseSupplierDialog"
    >
      <span>更换供应商后，对应的采购产品、订单类型都会清空</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="supplierDialogRefuse">取 消</el-button>
        <el-button type="primary" @click="supplierDialogConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="更换医院"
      :visible.sync="dialogVisible.contract"
      width="30%"
      :before-close="handleCloseContractDialog"
    >
      <span>更换医院后，对应的采购产品、订单类型都会清空</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="contractDialogRefuse">取 消</el-button>
        <el-button type="primary" @click="contractDialogConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as CONSTS from './supplier-and-contract.const';
import ElEditable from '@components/el-editable';
// import { querySupplierList, queryHospitalList } from '@api/guoke_deepexi_interface_center_v1';
import { selectDistributorList, selectHospList } from '@api/guoke_deepexi_interface_center_v1';
// import { hospitalOrderType, contract } from '@api/m_mall_web_v1';
export default {
  components: {
    ElEditable
  },
  props: {
    supplierId: String,
    contractId: String,
    busModel: String,
    products: {
      type: Array,
      default: () => []
    },
    onsignOrderType: Boolean,
    orderType: String,
    isFirstMount: Boolean,
    productLoading: Boolean,
    disabled: Boolean
  },
  data() {
    return {
      ...CONSTS,
      table_query: {},
      rows_supplies: [], // 产品线列表数据
      payload_contracts: [], // 产品线数据
      supplier_id: '',
      contract_id: '',
      full_data: {
        orgName: '',
        orgId: '',
        shortCode: '',
        contractName: '',
        contractCode: '',
        originalFactoryName: '',
        originalFactoryCode: '',
        customerName: '',
        accountNumber: ''
      },
      storaged: {
        supplier_id: '',
        contract_id: ''
      },
      dialogVisible: {
        supplier: false,
        contract: false
      },
      contractTableLoading: false
    };
  },
  computed: {
    // 判断是否存在产品信息或订单类型，如果存在则为true，用于在切换供应商或合同时提示
    isNeedAlert() {
      console.log(this.products)
      if(this.products.length > 0) {
        return true;
      }
      return false;
    }
  },
  watch: {
    supplierId: {
      handler: function(val, oldVal) {
        if (val !== '') {
          this.supplier_id = val;
          this.storaged.supplier_id = val;
          this.onLoadData();
          // 当重新获取合同列表时，手动清空合同绑定的及缓存的值
          // 如果是第一次加载，则不把合同置为空
          // 只要没切换supplierId，或者ContractId就视为第一次加载
          if (!this.isFirstMount) {
            this.contract_id = '';
            this.storaged.contract_id = '';
            this.full_data.contract = '';
            // 清空相应数据后还要更新
            this.$emit('update:contractId', this.contract_id);
          }
        }
      },
      immediate: true
    },
    contractId: {
      handler: function(val, oldVal) {
        this.contract_id = val;
        this.storaged.contract_id = val
      },
      immediate: true
    }
  },
  created() {
    this.getSuppliers();
  },
  methods: {
    getSuppliers() {
      this.$axios({
        method: 'post',
        url: selectDistributorList,
        data: {}
      })
      .then(res => {
        this.rows_supplies = res.data.payload || [];
      })
    },
    async onLoadData() {
      if (!this.supplier_id) {
        this.$message.error('请选择供应商');
        return;
      }
      this.contractTableLoading = true;
      this.$axios({
        method: 'post',
        url: `${selectHospList}?shortCode=${this.supplier_id}`,
        data: {
        }
      })
      .then(res => {
        this.payload_contracts = res.data.payload;
        let contract = this.payload_contracts.find(item => item.accountNumber === this.contract_id);
        // this.full_data.accountNumber = contract.accountNumber
        if (contract !== undefined) {
          const supplier = this.rows_supplies.find(item => item.shortCode === this.supplier_id);
          this.full_data.orgName = supplier.orgName;
          // this.full_data.orgId = supplier.orgId;
          this.full_data.shortCode = supplier.shortCode;
          Object.assign(this.full_data, contract);
          this.$emit('change', this.full_data);
        }
        console.log(this.full_data)
      })
      .finally(() => {
        this.contractTableLoading = false;
      });
    },
    supplierCommonProgress(supplierId) {
      // 走剩下的逻辑
      this.$emit('update:supplierId', supplierId);
      let suppliy = this.rows_supplies.find(item => item.shortCode === supplierId);
      // 为了上一层的取值，这里额外再赋值一下
      this.full_data.suppliy = suppliy;
      Object.assign(this.full_data, suppliy);
      // 这里通过emit给上级传递数据，触发watch，加载数据
      this.$emit('update:isFirstMount', false);
      this.$emit('change', this.full_data);
    },
    onChangeSupplier(value) {
      console.log(this.storaged.supplier_id)
      if (this.isNeedAlert) {
        this.dialogVisible.supplier = true;
      } else {
        this.storaged.supplier_id = value;
        this.supplierCommonProgress(value);
      }
      // // 如果存在暂存数据，那要显示弹窗，并给当前选中数据赋值
      // if (this.storaged.supplier_id) {
      //   this.dialogVisible.supplier = true;
      // } else {
      //   this.storaged.supplier_id = value;
      //   this.supplierCommonProgress(value);
      // }
    },
    supplierDialogConfirm() {
      this.dialogVisible.supplier = false;
      // 确定更新，要更新暂存数据，重新赋值
      this.storaged.supplier_id = this.supplier_id;
      console.log(this.storaged.supplier_id)
      // 加这个字段，是因为无论取消还是确定都要更新
      // this.needClearSupplier = true;
      this.supplierCommonProgress(this.supplier_id);
    },
    supplierDialogRefuse() {
      this.dialogVisible.supplier = false;
      // 取消的话，要把当前暂存的数据重新赋值给当前状态值
      console.log(this.storaged.supplier_id)
      this.supplier_id = this.storaged.supplier_id;
      // this.needClearSupplier = false;
      // this.supplierCommonProgress(this.supplier_id);
    },
    handleCloseSupplierDialog() {
      this.supplierDialogRefuse();
    },
    contractCommonProgress(contractId) {
      this.$emit('update:contractId', contractId);
      this.storaged.contract_id = contractId;
      let contract = this.payload_contracts.find(item => item.accountNumber === contractId);
      // 为了上一层的取值，这里额外再赋值一下
      this.$emit('update:isFirstMount', false);
      this.full_data.contract = contract;
      this.$emit('change', this.full_data);
    },
    onChangeContract(contractId) {
      console.log(this.isNeedAlert)
      if (this.isNeedAlert) {
        this.dialogVisible.contract = true;
      } else {
        this.storaged.contract_id = contractId;
        this.contractCommonProgress(contractId);
      }
    },
    contractDialogConfirm() {
      this.dialogVisible.contract = false;
      // 确定更新，要更新暂存数据，重新赋值
      this.storaged.contract_id = this.contract_id;
      console.log(this.contract_id)
      this.contractCommonProgress(this.contract_id);
    },
    contractDialogRefuse() {
      this.dialogVisible.contract = false;
      // 取消的话，要把当前暂存的数据重新赋值给当前状态值
      this.contract_id = this.storaged.contract_id;
      console.log(this.contract_id)
      // this.contractCommonProgress(this.contract_id);
    },
    handleCloseContractDialog() {
      this.contractDialogRefuse();
    }
  }
};
</script>

<style lang="less">
.w100p {
  width: 100%;
}
</style>
